﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using Devfw.OpenAuth;
using System.Net;

namespace Devfw.OpenAuth.Platform
{
    
    public class Sohu : ProviderBase
    {
        public Sohu( string oauth_consumer_key, string oauth_consumer_secret )
            : base( oauth_consumer_key, oauth_consumer_secret )
        {
            _core.AuthorizationType = AuthorizationType.HttpAuthorizationHeader;
        }

        public Sohu( string oauth_consumer_key, string oauth_consumer_secret, string oauth_token, string oauth_token_secret )
            : base( oauth_consumer_key, oauth_consumer_secret, oauth_token, oauth_token_secret, "1.0", SignatureType.HMACSHA1, AuthorizationType.HttpAuthorizationHeader )
        {
        }


        #region OAuth
        public RequestTokenResponse request_token()
        {
            return _core.request_token( "http://api.t.sohu.com/oauth/request_token" );
        }

        public void authorize( string oauth_token, string oauth_callback )
        {
            string url = _core.generate_authorize_url( "http://api.t.sohu.com/oauth/authorize", oauth_token, oauth_callback );
            HttpContext.Current.Response.Redirect( url );
        }

        public string GetAuthorizeUrl(string oauth_token, string oauth_callback)
        {
            if (!string.IsNullOrEmpty(oauth_token))
                return _core.generate_authorize_url("http://api.t.sohu.com/oauth/authorize", oauth_token, oauth_callback);

            return string.Empty;
        }

        public AccessTokenResponse access_token( string oauth_token, string oauth_token_screct, string oauth_verfier )
        {
            return _core.access_token( "http://api.t.sohu.com/oauth/access_token", oauth_token, oauth_token_screct, oauth_verfier );
        }
        #endregion

        public string statuses_update( string format, string status )
        {
            string response = _core.OpenAuthWebRequest( HttpWebMethod.POST, "http://api.t.sohu.com/statuses/update." + format, OAuthToken, OAuthTokenSecret,
                new ParameterCollection()
                {
                    new Parameter( "status", HttpUtility.UrlEncode( status ), ParameterType.Post )
                } );

            return response;
        }

        public string statuses_upload( string format, string status, string url )
        {
            WebClient client = new WebClient();
            byte[] b = client.DownloadData( url );
            string[] f = url.Split( '\\', '/' );
            return statuses_upload( format, status, b, f[f.Length - 1] );
        }

        public string statuses_upload( string format, string status, byte[] imageByte, string fileName )
        {
            var contentEncoding = "iso-8859-1";
            string fileData = System.Text.Encoding.GetEncoding( contentEncoding ).GetString( imageByte );

            string response = _core.OpenAuthFormDataPostWebRequest( "http://api.t.sohu.com/statuses/upload." + format, OAuthToken, OAuthTokenSecret,
            new ParameterCollection()
                {
                    new PostParameter( "status", HttpUtility.UrlEncode( status ) ),
                    new PostParameter( "pic", fileData, true,  "filename=\"" + fileName + "\"", false )
                } );

            return response;
        }

        public bool FriendshipsExistsByScreenname(string format, string TargetUser)
        {
            string response = _core.OpenAuthWebRequest(HttpWebMethod.GET, "http://api.t.sohu.com/friendships/show." + format, OAuthToken, OAuthTokenSecret,
                new ParameterCollection()
                {
                    
                    new Parameter( "target_screen_name", HttpUtility.UrlEncode( TargetUser ), ParameterType.Get )
                    
                    
                }, AuthorizationType.UrlQuery);

            xmlHelper help = new xmlHelper(response);
            string ex = help.getValue("/relationship/target/followed_by");
            return ex == "true";
        }

        //public bool FriendshipsExistsByUserid(string format, string TargetUser)
        //{
        //    string response = _core.OpenAuthWebRequest(HttpWebMethod.GET, "http://api.t.sohu.com/friendships/exists." + format, OAuthToken, OAuthTokenSecret,
        //        new ParameterCollection()
        //        {
                    
        //            new Parameter( "user_a", HttpUtility.UrlEncode( userida ), ParameterType.Get ),
        //            new Parameter( "user_b", HttpUtility.UrlEncode( useridb ), ParameterType.Get )
                    
        //        }, AuthorizationType.UrlQuery);

        //    return response.IndexOf("true") > 0;
        //}

        public string StatusesRepost(string format,string id,string status )
        {
            string response = _core.OpenAuthWebRequest( HttpWebMethod.POST, string.Format("http://api.t.sohu.com/statuses/transmit/{0}.{1}",id, format), OAuthToken, OAuthTokenSecret,
                new ParameterCollection()
                {
                    new Parameter( "status", HttpUtility.UrlEncode( status ), ParameterType.Post )                 
                } );

            return response;
        }

        public string StatusesComment(string format, string id, string comment)
        {
            string response = _core.OpenAuthWebRequest(HttpWebMethod.POST, string.Format("http://api.t.sohu.com/statuses/comment.{0}",format), OAuthToken, OAuthTokenSecret,
                new ParameterCollection()
                {
                    new Parameter( "id", id, ParameterType.Post ),                 
                    new Parameter( "comment", HttpUtility.UrlEncode( comment ), ParameterType.Post )                 
                });

            return response;
        }

        /// <summary>
        /// 返回好友列表
        /// </summary>
        /// <param name="format">格式（xml，json）</param>
        /// <param name="id">用户id，可选</param>
        /// <param name="page">页码</param>
        /// <param name="count">每页获取的用户数量，最多不超过20条，默认20条</param>
        /// <returns></returns>
        public string getFriendlist(string format, string id, string page, string count)
        {
            if (!string.IsNullOrEmpty(id))
                id = "/" + id;

            string response = _core.OpenAuthWebRequest(HttpWebMethod.GET, string.Format("http://api.t.sohu.com/statuses/friends{0}.{1}", id, format), OAuthToken, OAuthTokenSecret,
                new ParameterCollection()
                {
                    new Parameter( "page",  page , ParameterType.Get ),
                    new Parameter( "count",  count , ParameterType.Get )
                   
                });

            return response;
        }

        public string setSetFriendship(string format, string acttype, string id)
        {

            string response = _core.OpenAuthWebRequest(HttpWebMethod.POST, string.Format("http://api.t.sohu.com/friendships/{0}/{1}.{2}", acttype, id, format), OAuthToken, OAuthTokenSecret,
                new ParameterCollection()
                {
                    new Parameter( "source", HttpUtility.UrlEncode( _core.OAuthConsumerKey), ParameterType.Get )
                });

            return response;
        }

        public string getUserShow(string format, string id)
        {
            if (!string.IsNullOrEmpty(id))
                id = "/" + id;

            string response = _core.OpenAuthWebRequest(HttpWebMethod.GET, string.Format("http://api.t.sohu.com/users/show{0}.{1}", id, format), OAuthToken, OAuthTokenSecret);
            return response;
        }


        public string addFriend(string format,string id)
        {

            string response = _core.OpenAuthWebRequest(HttpWebMethod.POST, string.Format("http://api.t.sohu.com/friendships/create/{0}.{1}", id, format), OAuthToken, OAuthTokenSecret,
                new ParameterCollection()
                {
                    new Parameter( "source", HttpUtility.UrlEncode( _core.OAuthConsumerKey), ParameterType.Post )
                });

            return response;
        }


        public string removeFriend(string format, string id)
        {

            string response = _core.OpenAuthWebRequest(HttpWebMethod.POST, string.Format("http://api.t.sohu.com/friendships/destroy/{0}.{1}", id, format), OAuthToken, OAuthTokenSecret,
                new ParameterCollection()
                {
                    new Parameter( "source", HttpUtility.UrlEncode( _core.OAuthConsumerKey), ParameterType.Post )
                });

            return response;
        }
    }
}
